package com.hzw.saas.api.old.storage.enums;

import java.util.Objects;

import com.hzw.saas.common.config.util.AssertUtil;


/**
 * 资源状态枚举
 *
 * @author zzl
 * @since 12/24/2020
 */
public enum ResourceStatusEnum {

    // 正常状态
    NORMAL(200, "正常"),
    // 归档/回收
    ARCHIVED(300, "回收"),
    // 关联回收
    ARCHIVED_LINKED(301, "关联回收"), // 父目录为300，则子目录和文件为301
    // 删除
    DELETED(400, "删除"),
    // 关联删除
    DELETED_LINKED(401, "关联删除"), // 父目录为400，则子目录和文件为401
    // 覆盖删除
    DELETED_COVER(402, "覆盖删除"),  // 同名文件覆盖，被覆盖的文件标记为此状态
    ;

    private final Integer code;
    private final String text;

    ResourceStatusEnum(Integer code, String text) {
        this.code = code;
        this.text = text;
    }

    public Integer code() {
        return code;
    }

    public String text() {
        return text;
    }

    public static String text(Integer code) {
        for (ResourceStatusEnum value : ResourceStatusEnum.values()) {
            if (Objects.equals(value.code, code))
                return value.text;
        }
        return null;
    }

    public static ResourceStatusEnum instance(Integer code) {
        return instance(code, false);
    }

    public static ResourceStatusEnum instance(Integer code, boolean throwUnknown) {
        for (ResourceStatusEnum value : ResourceStatusEnum.values()) {
            if (Objects.equals(value.code, code))
                return value;
        }
        AssertUtil.assertThrow("资源状态异常，请设置正确的状态码", throwUnknown);
        return null;
    }

    /**
     * 获取关联状态
     *
     * @param code         状态码
     * @param throwUnknown 检查状态码是否存在，不存在则抛出异常
     * @return 关联状态
     */
    public static ResourceStatusEnum subInstance(Integer code, boolean throwUnknown) {
        ResourceStatusEnum instance = ResourceStatusEnum.instance(code, throwUnknown);
        return instance == ARCHIVED ? ARCHIVED_LINKED
            : instance == DELETED ? DELETED_LINKED
            : instance;
    }

    /**
     * 校验状态
     *
     * @param dest    校验基准
     * @param code    被校验值
     * @param throwEx 未通过是否抛出异常
     * @return 校验结果，true/false
     */
    public static boolean check(ResourceStatusEnum dest, Integer code, boolean throwEx) {
        ResourceStatusEnum instance = ResourceStatusEnum.instance(code, true);
        assert instance != null;
        boolean check = dest == instance;
        AssertUtil.assertThrow("资源状态异常：" + instance.text(), !check && throwEx);
        return check;
    }

    public static boolean isArchived(Integer code) {
        return Objects.equals(ResourceStatusEnum.ARCHIVED.code, code)
            || Objects.equals(ResourceStatusEnum.ARCHIVED_LINKED.code, code);
    }

    public static boolean isDeleted(Integer code) {
        return Objects.equals(ResourceStatusEnum.DELETED.code, code)
            || Objects.equals(ResourceStatusEnum.DELETED_LINKED.code, code)
            || Objects.equals(ResourceStatusEnum.DELETED_COVER.code, code);
    }
}
